package com.nineclock.approve.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.approve.dto.*;
import com.nineclock.approve.mapper.ApproveDefinitionMapper;
import com.nineclock.approve.pojo.ApproveDefinition;
import com.nineclock.approve.service.ApproveDefinitionService;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.threadlocal.CurrentUserHolder;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.common.utils.JsonUtils;
import com.nineclock.common.utils.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Service
@Slf4j
public class ApproveDefinitionServiceImpl implements ApproveDefinitionService {

    @Autowired
    ApproveDefinitionMapper approveDefinitionMapper;

    @Override
    public List<ApproveGroupDefinitionDto> queryApproveGroupDefinition() {
        List<ApproveGroupDefinitionDto> list = new ArrayList<>();

        //查询当前企业 的有效 审批流程
        LambdaQueryWrapper<ApproveDefinition> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApproveDefinition::getCompanyId, CurrentUserHolder.get().getCompanyId());
        wrapper.eq(ApproveDefinition::getIsValid, 1);

        List<ApproveDefinition> approveDefinitions = approveDefinitionMapper.selectList(wrapper);
        //根据 分类 对list集合进行分组

        Map<String, List<ApproveDefinition>> map = approveDefinitions.stream().collect(Collectors.groupingBy(ApproveDefinition::getGroupType));
        //把map集合转换 ApproveGroupDefinitionDto
        //map中的一个 键值对 应 一个 ApproveGroupDefinitionDto
        //获取map的key集合，然后循环
        for (String key : map.keySet()) {
            ApproveGroupDefinitionDto approveGroupDefinitionDto = new ApproveGroupDefinitionDto();
            approveGroupDefinitionDto.setGroupType(key);
            approveGroupDefinitionDto.setDefinitionList(map.get(key));

            //添加到集合中
            list.add(approveGroupDefinitionDto);
        }

        return list;

    }

    @Override
    public void saveApproveDefinition(ApproveDefinitionSaveDto approveDefinitionSaveDto) {
        if (approveDefinitionSaveDto == null || approveDefinitionSaveDto.getBaseData() == null) {
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        //获取基础数据
        ApproveDefinitionBaseDataDto baseData = approveDefinitionSaveDto.getBaseData();
        //新增
        if (baseData.getId() == null){
            //把参数中的 数据全部封装到 approveDefinition 对象
            //把baseData中的数据复制到 approveDefinition 对象
            ApproveDefinition definition = BeanHelper.copyProperties(baseData, ApproveDefinition.class);
            definition.setCompanyId(CurrentUserHolder.get().getCompanyId() + "");
            definition.setCreateTime(new Date());
            definition.setIsValid("1");
            definition.setDataFrom("1");
            definition.setTableName("flow_"+UUIDUtils.getUUID());

            //设置 谁可以发起这个审批
            List<AllowUserObjDto> allowUserJson = baseData.getAllowUserJson();

            //转换为json
            definition.setAllowUserJson(JsonUtils.toString(allowUserJson));
            //设置表单数据
            List<ApproveDefinitionTableDataDto> tableData = approveDefinitionSaveDto.getTableData();
            //设置表单数据
            definition.setFormJson(JsonUtils.toString(tableData));

            //设置表单中的列 数据
            List<ColumnObjDto> columnObjDtos = this.expandFieldKey(approveDefinitionSaveDto);
            definition.setColumns(JsonUtils.toString(columnObjDtos));


            //设置流程数据
            String flowData = approveDefinitionSaveDto.getFlowData();
            JSONArray jsonArray = JSONUtil.parseArray(flowData);
            //给每一个节点扩展 一个 字段
            this.expandParamWithNodeKey(jsonArray);
            definition.setFlowJson(JsonUtils.toString(jsonArray));

            approveDefinitionMapper.insert(definition);
        }
        //修改审批流程
        else{
            //根据id查询 流程定义对象
            ApproveDefinition definition = approveDefinitionMapper.selectById(baseData.getId());

            if(definition == null){
                throw new NcException(ResponseEnum.SERVER_ERROR);
            }

            //更新 数据
            //更新 基础信息
            definition.setGroupType(baseData.getGroupType());
            definition.setName(baseData.getName());
            definition.setSeq(baseData.getSeq());
            definition.setIcon(baseData.getIcon());
            definition.setDescription(baseData.getDescription());
            definition.setOpinionPrompt(baseData.getOpinionPrompt());
            definition.setOpinionRequired(baseData.getOpinionRequired());
            definition.setUpdateTime(new Date());

            //设置允许谁发起这个流程
            List<AllowUserObjDto> allowUserJson = baseData.getAllowUserJson();
            //转换为json
            definition.setAllowUserJson(JsonUtils.toString(allowUserJson));


            //设置表单信息
            List<ApproveDefinitionTableDataDto> tableData = approveDefinitionSaveDto.getTableData();
            definition.setFormJson(JsonUtils.toString(tableData));

            //设置表单中的列 数据
            List<ColumnObjDto> columnObjDtos = this.expandFieldKey(approveDefinitionSaveDto);
            definition.setColumns(JsonUtils.toString(columnObjDtos));

            //设置流程信息
            String flowData = approveDefinitionSaveDto.getFlowData();
            JSONArray jsonArray = JSONUtil.parseArray(flowData);
            //给每一个节点扩展 一个 字段
            this.expandParamWithNodeKey(jsonArray);

            definition.setFlowJson(JsonUtils.toString(jsonArray));

            approveDefinitionMapper.updateById(definition);
        }
    }

  /*  @Override
    public ApproveDefinitionResultDto queryById(String id) {
        if(id == null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        //根据id查询 流程定义对象
        ApproveDefinition definition = approveDefinitionMapper.selectById(id);

        if(definition == null){
            throw new NcException(ResponseEnum.SERVER_ERROR);
        }
        //获取 基础信息
        ApproveDefinitionBaseDataDto baseData = BeanHelper.copyProperties(definition, ApproveDefinitionBaseDataDto.class);

        //谁允许发起这个流程的json
        String allowUserJson = definition.getAllowUserJson();
        List<AllowUserObjDto> allowUserObjList = JsonUtils.toList(allowUserJson, AllowUserObjDto.class);
        baseData.setAllowUserJson(allowUserObjList);

        //获取表单 json数据
        String formJson = definition.getFormJson();
        List<ApproveDefinitionTableDataResultDto> tableDataResultList = JsonUtils.toList(formJson, ApproveDefinitionTableDataResultDto.class);


        String flowJson = definition.getFlowJson();

        ApproveDefinitionResultDto approveDefinitionResultDto = new ApproveDefinitionResultDto();
        //设置 属性值
        approveDefinitionResultDto
                .setBaseData(baseData)
                .setTableData(tableDataResultList)
                .setFlowData(flowJson);

        return approveDefinitionResultDto;
    }
*/

    private void expandParamWithNodeKey(JSONArray jsonArray) {
        for(int i = 0; i < jsonArray.size(); i++){
            JSONObject jsonNode = (JSONObject) jsonArray.get(i);

            String nodeKey = jsonNode.getStr("nodeKey");
            if(StrUtil.isEmpty(nodeKey)){
                jsonNode.put("nodeKey", UUIDUtils.getUUID());
            }

            //处理网关节点的内部节点 nodeKey
            String type = jsonNode.getStr("type");
            if("condition".equals(type)){

                JSONArray batchArray = (JSONArray) jsonNode.get("node");
                if(batchArray!=null && batchArray.size()>0){

                    for (int j = 0; j < batchArray.size(); j++) {
                        JSONArray innerArray = (JSONArray) batchArray.get(j);

                        if(innerArray!=null && innerArray.size()>0){
                            for (int k = 0; k < innerArray.size(); k++) {
                                JSONObject node = (JSONObject) innerArray.get(k);
                                if(!node.containsKey("nodeKey")){
                                    node.put("nodeKey", UUIDUtils.getUUID());
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 扩充参数 : fieldKey
     * @param approveDefinitionDto
     * @return
     */
    private List<ColumnObjDto> expandFieldKey(ApproveDefinitionSaveDto approveDefinitionDto) {
        List<ColumnObjDto> columns = new ArrayList<>();

        for (ApproveDefinitionTableDataDto tableData : approveDefinitionDto.getTableData()) {
            if(StrUtil.isEmpty(tableData.getFieldKey())){
                tableData.setFieldKey(UUIDUtils.getUUID());
            }

            columns.add(new ColumnObjDto(tableData.getFieldKey(), tableData.getLab(), tableData.getTitle(), "1"));
        }
        return columns;
    }


}
